package com.android.danaobank.widgets;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.android.danaobank.R;
import com.blankj.utilcode.util.ConvertUtils;

/**
 * ================================================
 * <p>
 * Created by ligang on 2020/9/19  8:43
 * ================================================
 */
public class ImageSpanTextView2 extends View {
    private Paint mTextPaint;

    public ImageSpanTextView2(Context context) {
        super(context);
        init();
    }

    public ImageSpanTextView2(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mTextPaint = new Paint();
        mTextPaint.setTextSize(ConvertUtils.sp2px(15));
        mTextPaint.setColor(Color.BLACK);
        mTextPaint.setAntiAlias(true);
        text = "国际半导体产业协会近日向美国政府发出警告，如果将中国芯片制造商中芯国际列入“实体清单”，将导致美国半导体产业每年";
    }

    private String text;

    private int width;

    private void setText(String text) {
        this.text = text;
    }


    private Bitmap bitmap;
    private Rect rectSrc;
    private RectF rectFDest = new RectF();

    @Override
    protected void onDraw(Canvas canvas) {
        if (width == 0) {
            width = getWidth();
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_shop_share_orange);
            rectSrc = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        }
        StringBuffer sb = new StringBuffer();
        int line = 0;
        for (int i = 0; i < text.length(); i++) {
            String s = String.valueOf(text.charAt(i));
            if (mTextPaint.measureText(sb.toString() + s) > width) {
                //换行
                String drawText = sb.toString();
                canvas.drawText(drawText, 0, 32 + 38 * line, mTextPaint);
                sb = new StringBuffer();
                line++;
            }
            sb.append(s);
        }
        canvas.drawText(sb.toString(), 0, 32 + 38 * line, mTextPaint);
        float x = mTextPaint.measureText(sb.toString());
        rectFDest.left = x + ConvertUtils.dp2px(5);
        rectFDest.top = 32 + 38 * line - ConvertUtils.dp2px(12);
        rectFDest.right = rectFDest.left + bitmap.getWidth();
        rectFDest.bottom = rectFDest.top + ConvertUtils.dp2px(15);
        canvas.drawBitmap(bitmap, rectSrc, rectFDest, null);
//        canvas.drawText("国际半导体产业协会近日向美国政府发出警告，如", 0, 50 + 50, mTextPaint);
//        canvas.drawText("果将中国芯片制造商中芯国际列入“实体清单”，将", 0, 50 + 50 * 2, mTextPaint);
//        canvas.drawText("导致美国半导体产业每年", 0, 50 + 50 * 3, mTextPaint);
    }
}
